#!/bin/bash

# Kubernetes Serverless (Fargate) 部署 Loki + Fluent Bit Sidecar + Grafana
# 适用于 AWS EKS Fargate 环境

set -e

echo "开始部署 Loki 日志系统到 Kubernetes Fargate..."

# 创建命名空间
echo "创建 monitor 命名空间..."
kubectl apply -f loki/deployment.yaml

# 添加 Helm 仓库
echo "添加 Grafana Helm 仓库..."
helm repo add grafana https://grafana.github.io/helm-charts
helm repo update

# 部署 Loki (Fargate 模式)
echo "部署 Loki (Fargate Serverless 模式)..."
helm upgrade --install loki grafana/loki \
  --version 6.30.0 \
  -n monitor \
  -f loki/values.yaml

# 部署 Fluent Bit ConfigMap
echo "部署 Fluent Bit ConfigMap (Sidecar 模式)..."
kubectl apply -f fluent-bit/configmap.yaml

# 部署 Grafana
echo "部署 Grafana..."
helm upgrade --install grafana grafana/grafana \
  --version 8.3.0 \
  -n monitor \
  -f grafana/values.yaml

echo ""
echo "=========================================="
echo "Fargate Serverless 部署完成！"
echo "=========================================="
echo ""
echo "📌 重要提示："
echo "Fargate 环境下不支持 DaemonSet，日志收集采用 Fluent Bit Sidecar 方式"
echo ""
echo "在您的应用 Deployment 中添加 Fluent Bit Sidecar 容器："
echo "参考示例: fluent-bit/sidecar-example.yaml"
echo ""
echo "获取 Grafana 管理员密码:"
echo "  kubectl get secret -n monitor grafana -o jsonpath='{.data.admin-password}' | base64 -d ; echo"
echo ""
echo "访问 Grafana (LoadBalancer 方式):"
echo "  kubectl get svc -n monitor grafana"
echo ""
echo "或使用端口转发:"
echo "  kubectl port-forward -n monitor svc/grafana 3000:80"
echo "  然后在浏览器中访问 http://localhost:3000"
echo ""
